
// lib
// script & methods & public
import toast from "components/toast";
// store
import { stateRoleModal } from "./state";
import { dataState } from "state/global";
import { TransferItem } from "antd/lib/transfer";
// service
import { editAdminRoleService, getAdminRoleService } from "biz/Admin/service";

export function createModalTransferData() {
  const result = dataState.roles.map((el) => {
    const item: TransferItem = {
      key: el.id.toString(),
      title: el.name,
      description: el.name,
    };
    return item;
  });
  return result;
}

export async function getAdminRoleList(model: AdminItemDto) {
  stateRoleModal.setTargetKeys([]);
  const result = await getAdminRoleService({ userId: model.userId });
  if (result.payload) {
    const list = result.payload.map((el: any) => el.id.toString());
    stateRoleModal.setTargetKeys(list);
  }
}

export async function letAdminRoleUpdate() {
  const user = stateRoleModal.getModal();
  const keys = stateRoleModal.getTargetKeys();
  if (!user) return;
  if (keys.length === 0) {
    toast.error("角色不能为空");
    return;
  }
  stateRoleModal.setModalLoading(true);
  const result = await editAdminRoleService({
    userId: user.userId,
    roleIds: keys,
  });
  stateRoleModal.setModalLoading(false);
  if (result.payload) {
    toast.success("设置成功");
    stateRoleModal.setModal(null);
    stateRoleModal.setTargetKeys([]);
  }
}

export async function showRoleModal(model: AdminItemDto) {
  stateRoleModal.setModal(model);
  getAdminRoleList(model);
}
